import * as config from '../config/config.js';

const ajax = {
    _request: (options) => {
        return new Promise((onResolve, onReject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = () => {
                if (xhr.readyState.toString() === '4') {
                    let response;
                    try {
                        response = JSON.parse(xhr.responseText);
                    }
                    catch (err) {
                        response = xhr.responseText;
                    }

                    if (xhr.status >= 200 && xhr.status < 400) {
                        const isSuccess = typeof response.err !== 'undefined' && response.err === config.XHR_RES_CODE.SUCCESS;

                        if (isSuccess) {
                            onResolve(response);
                        }
                        else {
                            onReject(response);
                        }
                    }
                    else {
                        onReject(response);
                    }
                }
            };

            if (options.type.toLowerCase() === 'get' && options.params != null) {
                const qs = Object.keys(options.params).map((key) => {
                    return `${key}=${options.params[key]}`;
                }).join('&').trim();

                options.url = qs === '' ? `${options.url}` : `${options.url}?${qs}`;
                options.params = null;
            }

            xhr.open(options.type, options.url, true);

            if (options.header) {
                Object.keys(options.header).forEach((key) => {
                    xhr.setRequestHeader(key, options.header[key]);
                });
            }

            xhr.timeout = 1000 * 30;
            xhr.send(options.params);
        });
    },
    get: (options) => {
        options.type = 'GET';
        return ajax._request(options);
    },
    post: (options) => {
        if (!options.header) { options.header = {}; }

        options.type = 'POST';
        options.header['Content-Type'] = 'application/json';
        options.params = JSON.stringify(options.params);
        return ajax._request(options);
    }
};

export default ajax;
